import { IndependentTablesDatabase } from '../lib/independent-tables-database';
import { RealSQLiteDatabase } from '../lib/real-sqlite-database';

/**
 * 数据迁移脚本：将共享属性表的数据迁移到设备独立的属性表中
 */
export class DataMigrationScript {
  private oldDb: RealSQLiteDatabase;
  private newDb: IndependentTablesDatabase;

  constructor() {
    this.oldDb = new RealSQLiteDatabase();
    this.newDb = new IndependentTablesDatabase();
  }

  /**
   * 执行完整的数据迁移
   */
  async migrate(): Promise<void> {
    console.log('开始数据迁移...');
    
    try {
      // 1. 迁移设备数据
      await this.migrateDevices();
      
      // 2. 迁移属性参数数据
      await this.migrateParameters();
      
      console.log('数据迁移完成！');
    } catch (error) {
      console.error('数据迁移失败:', error);
      throw error;
    }
  }

  /**
   * 迁移设备数据
   */
  private async migrateDevices(): Promise<void> {
    console.log('正在迁移设备数据...');
    
    const devices = this.oldDb.getAllDevices();
    console.log(`找到 ${devices.length} 个设备需要迁移`);

    for (const device of devices) {
      try {
        // 检查新数据库中是否已存在该设备
        const existingDevice = this.newDb.getDeviceById(device.device_id);
        
        if (!existingDevice) {
          // 插入设备到新数据库（会自动创建独立的属性表）
          this.newDb.insertDevice({
            device_id: device.device_id,
            name: device.name,
            classification_name: device.classification_name,
            classification_code: device.classification_code,
            specialty: device.specialty,
            naming_table_id: device.naming_table_id,
            position_table_id: device.position_table_id,
            base_params_table_id: device.base_params_table_id,
            tech_spec_table_id: device.tech_spec_table_id,
            sequence_number: device.sequence_number,
            remarks: device.remarks
          });
          
          console.log(`✓ 迁移设备: ${device.name} (ID: ${device.device_id})`);
        } else {
          console.log(`- 设备已存在: ${device.name} (ID: ${device.device_id})`);
        }
      } catch (error) {
        console.error(`✗ 迁移设备失败: ${device.name} (ID: ${device.device_id})`, error);
      }
    }
  }

  /**
   * 迁移参数数据
   */
  private async migrateParameters(): Promise<void> {
    console.log('正在迁移参数数据...');
    
    const devices = this.oldDb.getAllDevices();
    
    for (const device of devices) {
      console.log(`正在迁移设备 ${device.name} (ID: ${device.device_id}) 的参数...`);
      
      try {
        // 迁移命名参数
        await this.migrateNamingParameters(device.device_id);
        
        // 迁移位置参数
        await this.migratePositionParameters(device.device_id);
        
        // 迁移基础参数
        await this.migrateBaseParameters(device.device_id);
        
        console.log(`✓ 完成设备 ${device.name} 的参数迁移`);
      } catch (error) {
        console.error(`✗ 设备 ${device.name} 参数迁移失败:`, error);
      }
    }
  }

  /**
   * 迁移命名参数
   */
  private async migrateNamingParameters(deviceId: number): Promise<void> {
    const parameters = this.oldDb.getNamingParametersByDeviceId(deviceId);
    
    for (const param of parameters) {
      try {
        this.newDb.insertNamingParameter(deviceId, {
          sequence: param.sequence || '',
          parameter_name: param.parameter_name,
          parameter_value: param.parameter_value || '',
          data_type: param.data_type || '',
          example_description: param.example_description || '',
          measurement_class: param.measurement_class || '',
          data_source: param.data_source || '',
          is_required: param.is_required || false
        });
      } catch (error) {
        console.error(`  ✗ 命名参数迁移失败: ${param.parameter_name}`, error);
      }
    }
    
    console.log(`  ✓ 迁移了 ${parameters.length} 个命名参数`);
  }

  /**
   * 迁移位置参数
   */
  private async migratePositionParameters(deviceId: number): Promise<void> {
    const parameters = this.oldDb.getPositionParametersByDeviceId(deviceId);
    
    for (const param of parameters) {
      try {
        this.newDb.insertPositionParameter(deviceId, {
          sequence: param.sequence || '',
          parameter_name: param.parameter_name,
          parameter_value: param.parameter_value || '',
          data_type: param.data_type || '',
          example_description: param.example_description || '',
          measurement_class: param.measurement_class || '',
          data_source: param.data_source || '',
          is_required: param.is_required || false
        });
      } catch (error) {
        console.error(`  ✗ 位置参数迁移失败: ${param.parameter_name}`, error);
      }
    }
    
    console.log(`  ✓ 迁移了 ${parameters.length} 个位置参数`);
  }

  /**
   * 迁移基础参数
   */
  private async migrateBaseParameters(deviceId: number): Promise<void> {
    const parameters = this.oldDb.getBaseParametersByDeviceId(deviceId);
    
    for (const param of parameters) {
      try {
        this.newDb.insertBaseParameter(deviceId, {
          sequence: param.sequence || '',
          parameter_name: param.parameter_name,
          parameter_value: param.parameter_value || '',
          data_type: param.data_type || '',
          measurement_unit: param.measurement_unit || '',
          example_description: param.example_description || '',
          measurement_class: param.measurement_class || '',
          data_source: param.data_source || '',
          is_required: param.is_required || false
        });
      } catch (error) {
        console.error(`  ✗ 基础参数迁移失败: ${param.parameter_name}`, error);
      }
    }
    
    console.log(`  ✓ 迁移了 ${parameters.length} 个基础参数`);
  }

  /**
   * 验证迁移结果
   */
  async validateMigration(): Promise<boolean> {
    console.log('正在验证迁移结果...');
    
    const oldDevices = this.oldDb.getAllDevices();
    const newDevices = this.newDb.getAllDevices();
    
    if (oldDevices.length !== newDevices.length) {
      console.error(`设备数量不匹配: 原始 ${oldDevices.length}, 新 ${newDevices.length}`);
      return false;
    }
    
    for (const oldDevice of oldDevices) {
      const newDevice = this.newDb.getDeviceById(oldDevice.device_id);
      if (!newDevice) {
        console.error(`设备未找到: ${oldDevice.device_id}`);
        return false;
      }
      
      // 验证参数数量
      const oldNamingParams = this.oldDb.getNamingParametersByDeviceId(oldDevice.device_id);
      const newNamingParams = this.newDb.getDeviceNamingParameters(oldDevice.device_id);
      
      if (oldNamingParams.length !== newNamingParams.length) {
        console.error(`设备 ${oldDevice.device_id} 命名参数数量不匹配`);
        return false;
      }
      
      const oldPositionParams = this.oldDb.getPositionParametersByDeviceId(oldDevice.device_id);
      const newPositionParams = this.newDb.getDevicePositionParameters(oldDevice.device_id);
      
      if (oldPositionParams.length !== newPositionParams.length) {
        console.error(`设备 ${oldDevice.device_id} 位置参数数量不匹配`);
        return false;
      }
      
      const oldBaseParams = this.oldDb.getBaseParametersByDeviceId(oldDevice.device_id);
      const newBaseParams = this.newDb.getDeviceBaseParameters(oldDevice.device_id);
      
      if (oldBaseParams.length !== newBaseParams.length) {
        console.error(`设备 ${oldDevice.device_id} 基础参数数量不匹配`);
        return false;
      }
    }
    
    console.log('✓ 迁移验证通过');
    return true;
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    this.oldDb.close();
    this.newDb.close();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const migration = new DataMigrationScript();
  
  migration.migrate()
    .then(() => migration.validateMigration())
    .then((isValid) => {
      if (isValid) {
        console.log('🎉 数据迁移成功完成！');
      } else {
        console.error('❌ 数据迁移验证失败');
        process.exit(1);
      }
    })
    .catch((error) => {
      console.error('❌ 数据迁移过程中发生错误:', error);
      process.exit(1);
    })
    .finally(() => {
      migration.cleanup();
    });
}
